package com.villaday.idf.custom;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.ScreenshotUtils;
import com.villaday.idf.util.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;


/**
 * 确认 对话框
 */
public class ErWeiMaDialog extends BaseDialog implements View.OnClickListener {

    private String materialId;

    public static ErWeiMaDialog newInstance(String url) {
        ErWeiMaDialog dialog = new ErWeiMaDialog();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);

        dialog.setArguments(bundle);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //取消标题显示
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        Window window = getDialog().getWindow();
        View view = inflater.inflate(R.layout.erweima_confirm,
                ((ViewGroup) window.findViewById(android.R.id.content)), false);
        //必须设置，否则不能全屏
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //宽度撑满
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);
        //进入退出动画
        window.setWindowAnimations(R.style.animTranslateBottom);
        SimpleDraweeView viewById = (SimpleDraweeView) view.findViewById(R.id.sdv);
        viewById.setImageURI(getArguments().getString("url"));
        view.findViewById(R.id.tv_wx).setOnClickListener(this);
        view.findViewById(R.id.tv_pyq).setOnClickListener(this);
        view.findViewById(R.id.tv_save).setOnClickListener(this);
        view.findViewById(R.id.ll).setOnClickListener(this);

        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        v.setTag(getArguments().get("url"));
        onItemClickListener.onItemClick(v);


        dismiss();
    }

    //根据网络图片url路径保存到本地
    public static final File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context);

            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {
            return file;
        } else {
            return null;
        }
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        String imageFileName = getDefaultPath() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }

    //获取默认存储地址  参数要传空
    private static String getDefaultPath() {
        SimpleDateFormat sdf24H = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
        String format = sdf24H.format(new Date(System.currentTimeMillis()));
        return format;

    }
    /**
     * @param flag 0分享给微信好友  1分享到朋友圈
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void shareImage(final int flag, final List<String> images) {

        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        IWXAPI api = WXAPIFactory.createWXAPI(getContext(), Constant.ID.WeChat_APP_ID, true);
        api.registerApp(Constant.ID.WeChat_APP_ID);
        if (!api.isWXAppInstalled()) {//未安装微信
            ToastUtil.initToast(getContext(), "您未安装微信");

        } else {
            final List<File> files = new ArrayList<>();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //这一步一定要clear,不然分享了朋友圈马上分享好友图片就会翻倍
                    files.clear();

                    try {

                        for (int i = 0; i < images.size(); i++) {
                            File file = saveImageToSdCard(getContext(), images.get(i));
                            files.add(file);
                        }

                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        intent.setType("image/*");
                        ArrayList<Uri> imageUris = new ArrayList<Uri>();
                        for (File f : files) {
                            imageUris.add(Uri.fromFile(f));
                        }

                        intent.putExtra(Intent.EXTRA_STREAM, imageUris.get(0));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }


    }

}
